package com.shycloud.mido.music.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.common.minio.enums.BucketEnum;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.music.domain.MisMusicCollection;
import com.shycloud.mido.music.mapper.MisMusicCollectionMapper;
import com.shycloud.mido.music.vo.MisMusicBannerVO;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.music.mapper.MisMusicBannerMapper;
import com.shycloud.mido.music.domain.MisMusicBanner;
import com.shycloud.mido.music.service.MisMusicBannerService;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * Banner相关服务
 */
@Service
@Slf4j
@AllArgsConstructor
public class MisMusicBannerServiceImpl extends
		ServiceImpl<MisMusicBannerMapper, MisMusicBanner> implements MisMusicBannerService {

	private MisMusicBannerMapper misMusicBannerMapper;

	/** minio 交互类 */
	private MinioTemplate minioTemplate;

	/** 曲集 Mapper */
	private MisMusicCollectionMapper collectionMapper;

	/**
	 * 上传 Banner 图片，并且关联到一个已有或者新增的类别里
	 *
	 * @param imgList    图片集合
	 * @param categoryId 分类 ID
	 * @param optId      代理商 ID
	 * @return
	 */
	@Override
	public List<Map<String, String>> batchUploadBanners(
			List<MultipartFile> imgList, Integer categoryId, Integer optId, String name) {

		List<Map<String, String>> returnList = new ArrayList<>();

		try {

			for (MultipartFile file : imgList) {

				//初始化map结果集
				Map<String, String> resultMap = new HashMap<>(4);

				//提取后缀
				String fileName = file.getOriginalFilename().replaceAll(" ", "");
				//提取图片名称
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

				String uuid = UUID.randomUUID().toString();
				//提取图片名称
				String imgName = uuid.replace("-", "") + "." + suffix;
				//名称
				resultMap.put("name", imgName);
				//上传操作指定返回域名
				String imgUrl = minioTemplate.uploadFileWX(file.getInputStream(), imgName,
						BucketEnum.ZEBRA_BANNER.getBucketName(),
						BucketEnum.ZEBRA_BANNER.getCdnUrl());

				resultMap.put("url", imgUrl);

				//将结果插入到数据库
				MisMusicBanner entity = new MisMusicBanner();
				entity.setCategoryId(categoryId);
				entity.setImgUrl(imgUrl);
				entity.setStatus(0);
				entity.setAssociateType(0);
				//暂时设为0，表示没有关联曲集ID
				entity.setCollectionId(0);
				entity.setLink("");
				//创建时间
				entity.setCreateTime(LocalDateTime.now());

				//代理商上传banner的场合,需要审核图片
				if (optId != 999999) {
					//待审核
					entity.setStatus(-1);
					//代理商 ID
					entity.setOptId(optId);
					//banner名称
					entity.setName(name);
				}

				int res = misMusicBannerMapper.insert(entity);

				resultMap.put("bannerId", String.valueOf(entity.getId()));
				//表示还未关联
				resultMap.put("associateType", "0");
				if (res != 1) {
					resultMap.put("error", "图片数据插入失败，请重新上传");
					returnList.add(resultMap);
					return returnList;
				}
				returnList.add(resultMap);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnList;
	}

	@Override
	public IPage<MisMusicBannerVO> getAllBanners(Integer current, Integer size, Integer categoryId,
			Integer optId) {
		return misMusicBannerMapper.getAllBanners(new Page<>(current, size), categoryId, optId);
	}

	@Override
	public Boolean associateBanner(String link, String collection, Integer bannerId,
			Integer associateType) {
		Integer collectionId = null;
		MisMusicBanner entity = new MisMusicBanner();
		entity.setId(bannerId);
		entity.setAssociateType(associateType);
		//if (!StringUtils.isEmpty(link)) {
		entity.setLink(link);
		//entity.setAssociateType(2);
		//}

		if (!StringUtils.isEmpty(collection)) {
			//collection有可能是曲集名，有可能是曲集ID，这里做下兼容
			try {
				collectionId = Integer.parseInt(collection);

				MisMusicCollection existing = collectionMapper.selectOne(
						new QueryWrapper<MisMusicCollection>().eq("id", collectionId));

				if (existing == null) {
					throw new BusinessException("未找到曲集，请检查曲集ID是否正确!");
				}

				entity.setCollectionId(Integer.valueOf(collection));
			} catch (NumberFormatException e) {
				log.info("传入曲集中文名称，无法解析成数字...将继续使用中文作为collection");
				List<MisMusicCollection> collectionList = collectionMapper.selectList(
						new QueryWrapper<MisMusicCollection>().eq("name", collection));

				if (collectionList == null || collectionList.size() == 0) {
					throw new BusinessException("未找到曲集，请检查曲集名称是否正确!");
				}

				//返回第一个匹配名称的曲集
				entity.setCollectionId(collectionList.get(0).getId());
			}

			entity.setAssociateType(1);
		}
		misMusicBannerMapper.updateById(entity);

		return null;
	}

	@Override
	public Boolean confirmAdding(String link, Integer collectionId, Integer bannerId) {
		return null;
	}

	@Override
	public Boolean disableBanner(Integer bannerId) {

		MisMusicBanner entity = new MisMusicBanner();
		entity.setId(bannerId);
		entity.setStatus(1);
		return misMusicBannerMapper.updateById(entity) == 1 ? true : false;

	}
}
